define([
    'jquery',
    'underscore',
    'backbone',
    //'text!templates/form/form_add_admin.html'
    ], function($, _, Backbone,loginTemplate){
        var $html_loadding = '<div class="caculation-report"><img style="margin-left:170px" src="'+$template_admincp_url+'img/standard/loaders/loading64.gif"/></div>';
        var galleryView = Backbone.View.extend({
            el: $("#main"),
            initialize: function(){
				
            },
            events: {
                
            },

            index: function(){
                var url = location.href;
                if(typeof oTable != "undefined"){
                    $("#table_gallery").dataTable().fnDestroy();
                }
                oTable = $('#table_gallery').dataTable({
                    "sDom": "<'row'<'col-lg-8'l><'col-lg-1 button_create'><'col-lg-3'f>r>t<'row'<'col-lg-6'i><'col-lg-6'p>>",
                    "sPaginationType": "bootstrap",
                    "bJQueryUI": false,
                    "bAutoWidth": false,
                    "oLanguage": {
                        "sUrl": $base_url+"public/templates/admincp/js/language/datatable.vn.txt"
                    },
                    "sScrollX": "100%",
                    //"sScrollXInner": "100%",
                    "bScrollCollapse": true,
                    "iDisplayLength": 10,
                    "iDisplayStart": 0,
                    "bProcessing": true,
                    "bRetrieve": true,
                    "aaSorting": [],
                    "bServerSide": true,
                    "sAjaxSource": url,
                    "fnServerData": function(sSource, aoData, fnCallback, oSettings) {
                        if(typeof filters != "undefined"){
                            obj_tmp = new Object;
                            $.each(filters, function(name, value){
                                obj_tmp[name] = value;
                            });
                            aoData.push({
                                name: "myFilter",
                                value: JSON.stringify(obj_tmp)
                            });
                        }
                        $.ajax( {
                            "dataType": 'json',
                            "type": "POST",
                            "url": sSource,
                            "data": aoData,
                            success: function(rs){
                                ids = rs.my_id;
                                fnCallback(rs);
                            }
                        });

                    },
                    "aoColumns": [
                        {
                            // "mData": "admin_name",
                            "sType": "string",
                            "swidth": "25%",
                            "sClass": "string",
                            "sName": "cata_name"
                        },
						{
                            // "mData": "admin_name",
                            "sType": "string",
                            "swidth": "25%",
                            "sClass": "string",
                            "sName": "gallery_name"
                        },
                        {
                            // "mData": "admin_name",
                            "sType": "string",
                            "swidth": "25%",
                            "sClass": "string",
                            "sName": "date_add"
                        },
                        {
                            // "mData": "action",
                            "sType": "string",
                            "swidth": "3%",
                            "sClass": "icon_table",
                            "bSortable": false
                        }
                    ],

                    fnInitComplete: function()
                    {
                        $(this).slideDown(200);
                        $(".button_create").html('<button class="btn btn-primary btn-create" type="button">Create New</button>');
                        $(".btn-create").click(function(){
                            window.location.href = $admincp_url+'gallery/add';
                        });
                    }
                });
                $('.dataTables_length select').uniform();
                $('.dataTables_paginate > ul').addClass('pagination');
            },
            
            add: function(){
                $('#catalogue').select2({placeholder: "Select Catalogue"});
                tinymce.init({
                    selector: "textarea.gallery_description",
                    theme: "modern",
                    plugins: [
                        "advlist autolink lists link charmap print preview hr anchor pagebreak",
                        "searchreplace visualblocks visualchars code fullscreen",
                        "insertdatetime media nonbreaking save table contextmenu directionality",
                        "emoticons template paste textcolor"
                    ],
                    toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link",
                    toolbar2: "print preview media | forecolor backcolor emoticons",
                    image_advtab: true,
                    relative_urls: false
                });
                $("#form").validate({
                    ignore: null,
                    ignore: 'input[type="hidden"]',
                    rules: {
                        agree: "required"
                    },
                    submitHandler: function(form){
                        form.submit();
                    }
                });
            },

            edit: function(){
                $('#catalogue').select2({placeholder: "Select Catalogue"});
                tinymce.init({
                    selector: "textarea.gallery_description",
                    theme: "modern",
                    plugins: [
                        "advlist autolink lists link charmap print preview hr anchor pagebreak",
                        "searchreplace visualblocks visualchars code fullscreen",
                        "insertdatetime media nonbreaking save table contextmenu directionality",
                        "emoticons template paste textcolor"
                    ],
                    toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link",
                    toolbar2: "print preview media | forecolor backcolor emoticons",
                    image_advtab: true,
                    relative_urls: false
                });
                $("#form").validate({
                    ignore: null,
                    ignore: 'input[type="hidden"]',
                    rules: {
                        agree: "required"
                    },
                    submitHandler: function(form){
                        form.submit();
                    }
                });
            },

            upload: function(){
                $(".deleteImage").click(function(){
                    var id = $(this).attr('ids');
                    var $this = $(this);
                    bootbox.confirm("Are you sure?", function(result) {
                        if(result == true){
                            $.ajax({
                                url: $admincp_url + 'gallery/deleteImage',
                                type: 'post',
                                data: 'id='+id,
                                async: false,
                                success: function(){
                                    $this.parent().remove();
                                }
                            });
                        }
                    });
                });
                
                $("#saveOrderImages").click(function(){
                	var idGal = $("#idGal").val();
                	var arrData = [];
                	$.each( $(".orderImages"), function( value ) {
				arrData.push({'id': $(this).attr('ids'), 'value': $(this).val()});
			});
			var dataJson = JSON.stringify(arrData);
                	bootbox.confirm("Are you sure?", function(result) {
                        if(result == true){
                            $.ajax({
                                url: $admincp_url + 'gallery/saveOrderImages',
                                type: 'post',
                                data: 'idGal='+idGal+'&dataJson=' +dataJson ,
                                async: false,
                                success: function(){
                                    
                                }
                            });
                        }
                    });
                  
                });

                var dropbox = $('#dropbox'),
                    message = $('.message', dropbox);
                dropbox.filedrop({
                    // The name of the $_FILES entry:
                    paramname:'pic',
                    
                    maxfiles: 20,
                    maxfilesize: 2,
                    url: $admincp_url+'gallery/do_upload',
                    data: {
                        idGal: function(){
                           var idGal = $("#idGal").val();
                           return idGal;
                        },
                        pathGal: function(){
                           var pathGal = $("#pathGal").val();
                           return pathGal;
                        }
                    },
                    uploadFinished:function(i,file,response){
                        $.data(file).addClass('done');
                        // response is the JSON object that post_file.php returns
                    },
                    
                    error: function(err, file) {
                        switch(err) {
                            case 'BrowserNotSupported':
                                showMessage('Your browser does not support HTML5 file uploads!');
                                break;
                            case 'TooManyFiles':
                                alert('Too many files! Please select 20 at most! (configurable)');
                                break;
                            case 'FileTooLarge':
                                alert(file.name+' is too large! Please upload files up to 2mb (configurable).');
                                break;
                            default:
                                break;
                        }
                    },
                    
                    // Called before each upload is started
                    beforeEach: function(file){
                        if(!file.type.match(/^image\//)){
                            alert('Only images are allowed!');
                            
                            // Returning false will cause the
                            // file to be rejected
                            return false;
                        }
                    },
                    
                    uploadStarted:function(i, file, len){
                        createImage(file);
                    },
                    
                    progressUpdated: function(i, file, progress) {
                        $.data(file).find('.progress').width(progress);
                    }
                     
                });
                
                var template = '<div class="preview">'+
                                    '<span class="imageHolder">'+
                                        '<img />'+
                                        '<span class="uploaded"></span>'+
                                    '</span>'+
                                    '<div class="progressHolder">'+
                                        '<div class="progress"></div>'+
                                    '</div>'+
                                '</div>'; 
                
                
                function createImage(file){

                    var preview = $(template), 
                        image = $('img', preview);
                        
                    var reader = new FileReader();
                    
                    image.width = 100;
                    image.height = 100;
                    
                    reader.onload = function(e){
                        
                        // e.target.result holds the DataURL which
                        // can be used as a source of the image:
                        
                        image.attr('src',e.target.result);
                    };
                    
                    // Reading the file as a DataURL. When finished,
                    // this will trigger the onload function above:
                    reader.readAsDataURL(file);
                    
                    message.hide();
                    preview.appendTo(dropbox);
                    
                    // Associating a preview container
                    // with the file, using jQuery's $.data():
                    
                    $.data(file,preview);
                }

                function showMessage(msg){
                    message.html(msg);
                }
            },

            render: function(){
                if(typeof this[$app.action] != 'undefined'){
                    new this[$app.action];
                }
            }
        });
        return galleryView = new galleryView;
    });